<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/modules/index/css/base.css">
    <link rel="stylesheet" href="/static/modules/index/css/style.css">
    <!--<link rel="stylesheet" href="/static/modules/index/css/elementui.css"> -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <link rel="stylesheet" href="/static/modules/index/css/swiper.min.css">
    <link rel="stylesheet" href="/static/modules/index/css/video-js.min.css">
    <script src="/static/modules/index/js/vue.js"></script>
    <script src="/static/modules/index/js/mqtt.min.js"></script>
    <script src="/static/modules/index/js/axios.min.js"></script>
    <script src="/static/modules/index/js/video.min.js"></script>
    <script src="/static/modules/index/js/vue-router.js"></script>
    <script src="/static/modules/index/js/elementui.js"></script>
    <script src="/static/modules/index/js/md5.js"></script>
    <style>
        html{
            height: 100%;
            width: 100%;
            position: relative;
            overflow: hidden;
        }
        body {
            background: #eee;
            font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
            font-size: 14px;
            color:#000;
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            position: relative;
            overflow-y: scroll;
        }
        #app::-webkit-scrollbar {
            display: none;
        }
        .swiper-container {
            width: 100%;
            height: 100%;
            margin-left: auto;
            margin-right: auto;
        }
        .swiper-slide {
            font-size: 18px;
            height: calc((100% - 30px) / 2);

            /* Center slide text vertically */
            display: -webkit-box;
            display: -ms-flexbox;
            display: -webkit-flex;
            display: flex;
            -webkit-box-pack: center;
            -ms-flex-pack: center;
            -webkit-justify-content: center;
            justify-content: center;
            -webkit-box-align: center;
            -ms-flex-align: center;
            -webkit-align-items: center;
            align-items: center;
        }
        .Thead2 {
            position: relative;
            font-size: 15px;
            color: #888;
            border-left: 5px solid #44b549;
            padding-left: 10px;
            margin: 12px 10px;
        }
    </style>
</head>

<body>
<div id="app"
     v-loading="loading"
     element-loading-text="数据获取中..."
     element-loading-spinner="el-icon-loading"
     element-loading-background="rgba(0, 0, 0, 0.8)"
     style="position: relative;height: 100%;">
    <div v-show="videoisplay">
        <video
                id="my-player"
                class="video-js"
                data-setup='{}'
                >
            <!-- <source src="//vjs.zencdn.net/v/oceans.mp4" type="video/mp4"></source>
            <source src="http://ivi.bupt.edu.cn/hls/cctv6hd.m3u8" type="application/x-mpegURL">
            -<source src="//vjs.zencdn.net/v/oceans.webm" type="video/webm"></source>
             <source src="//vjs.zencdn.net/v/oceans.ogv" type="video/ogg"></source> -->
            <p class="vjs-no-js">
                To view this video please enable JavaScript, and consider upgrading to a
                web browser that
                <a href="https://videojs.com/html5-video-support/" target="_blank">
                    supports HTML5 video
                </a>
            </p>
        </video>
    </div>
    <div v-show="goodsisshow" style="position: relative;height: 100%;">
        <div>
            <el-menu
                    :default-active="activeIndex2"
                    class="el-menu-demo"
                    mode="horizontal"
                    @select="handleSelect"
                    background-color="#545c64"
                    text-color="#fff"
                    active-text-color="#ffd04b">
                <el-menu-item index="-1"> 全部</el-menu-item>
                <el-menu-item v-for="(item,index) in goodscategorys" :key="index" :index="''+item.id"> {{ item.name }}</el-menu-item>
            </el-menu>
        </div>
        <div style="position: relative;height: 100%;" v-show="goods.length">
            <div class="swiper-container">
                <div class="swiper-wrapper">
                    <div class="swiper-slide" v-for="(itemgoods,index) in goods" :key="index">
                        <div style="white-space:normal;">
                            <div style="padding: 5px;">
                                <el-image
                                        style="width: 250px; height: 250px;"
                                        v-bind:src="itemgoods.image">
                                </el-image>
                            </div>
                            <div style="padding:3px;text-align: center;font-size: 15px;">
                                {{ itemgoods.goodsname }}
                            </div>
                            <div style="padding:6px;text-align: center;color:#F00;font-size: 24px;">
                                ￥{{ itemgoods.money }}
                            </div>
                            <div style="text-align: center;">
                                <el-button type="primary" round style="width: 100%;" @click.native="goodscontent(itemgoods.id)">我要购买</el-button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Add Arrows -->
                <div class="swiper-button-next"></div>
                <div class="swiper-button-prev"></div>
            </div>
        </div>
    </div>
    <el-dialog title="" :visible.sync="dialogTableVisible" width="40%">
        <el-container :model="gridData">
            <el-header style="display:inline;height: 215px;">
                <div style="float:left;width: 50%;">
                    <div align="center">
                        <el-image
                                style="width: 220px; height: 220px;"
                                :src="gridData.image">
                        </el-image>
                    </div>
                </div>
                <div style="float:left;width: 50%;">
                    <div align="center">
                        <div style="padding:3px;text-align: center;font-size: 15px;height: 50px;">
                            {{ gridData.goodsname }}
                        </div>
                        <div style="padding:10px;text-align: center;color:#F00;font-size: 25px;">
                            ￥{{ gridData.money }}
                        </div>
                        <div style="padding: 10px;">
                            <el-input-number v-model="goodsnum" @change="goodshandleChange" :min="1" :max="gridData.curamount" label="请选择购买数量"></el-input-number>
                        </div>
                        <div style="text-align: center;padding: 10px;">
                            <el-button type="primary" round style="width: 100%;" @click.native="payment(gridData.goodsid)">确认购买</el-button>
                        </div>
                    </div>
                </div>
            </el-header>
            <el-main>
                <el-divider></el-divider>
                <div style="width: 100%;">
                    <header class="Thead2" style="text-align: left;padding: 5px;">商品简介</header>
                    <div style="line-height: 23px;">{{ gridData.introduce }}</div>
                </div>
            </el-main>
        </el-container>
     </el-dialog>
    <el-dialog title="" :visible.sync="paymentdialogTableVisible" width="40%">
        <el-container :model="gridData2">
            <el-header>
                <div style="padding:6px;text-align: center;color:#F00;font-size: 26px;">
                    付款金额：{{ gridData2.money }} 元
                </div>
            </el-header>
            <!--<el-divider></el-divider> -->
            <el-main style="display:inline;text-align: center;font-size: 20px;">
                <div style="float:left;width: 50%;">
                    <div align="center" style="padding: 15px;">
                        支付宝扫码
                    </div>
                    <div align="center" style="padding: 5px;">
                        <el-image
                                style="width: 220px; height: 220px;"
                                :src="gridData2.zhifubaoeqcode">
                        </el-image>
                    </div>
                </div>
                <div style="float:left;width: 50%;">
                    <div align="center" style="padding: 15px;">
                        微信扫码
                    </div>
                    <div align="center" style="padding: 5px;">
                        <el-image
                                style="width: 220px; height: 220px;"
                                :src="gridData2.weixineqcode">
                        </el-image>
                    </div>
                </div>
            </el-main>
        </el-container>
    </el-dialog>
</div>

<script src="/static/modules/index/js/swiper.min.js"></script>

<script>
    var myplayer = null;
    var mqttclient = null;
    var swiperslide = null;

    new Vue({
        el: '#app',
        props: {
            index:  Number | String,
            goods: {
                type: Array,
                default: () => []
            },
        },
        data() {
            return {
                videoisplay:false,
                goodsisshow:true,
                activeIndex2: '-1',
                machine_id : 0,
                playerid : 0,
                paymentcode : '',
                loading : false,
                goodsnum : 1,
                goodscategorys: {
                    type: Array,
                    default: () => []
                },
                dialogTableVisible:false,
                gridData:[],
                paymentdialogTableVisible:false,
                gridData2:[],
            }
        },
        mounted: function() {
            this.InitVideoPlayer();
            this.Initswiperslide();
            this.InitOther();
            this.InitMqtt();
        },
        destroyed: function () {
            console.log("Hall leave.");
            mqttclient.end();
        },
        methods: {
            payment(goodsid) {
                var self = this;

                this.dialogTableVisible=false;

                //生成付款码用于双向验证
                var a=new Date();
                var paymentcodestr = a.toString()+self.playerid+goodsid+self.machine_id+self.goodsnum;
                this.paymentcode = hex_md5(paymentcodestr);

                axios.get("{:url('api/mobile/generatemachineeqcode')}", {
                    params: {
                        goodsid : goodsid,
                        userid : self.playerid,
                        machineid : self.machine_id,
                        unitprice : self.gridData['money'],
                        cargoway : self.gridData['cargoway'],
                        goodsnum : self.goodsnum,
                        paymentcode : self.paymentcode,
                    }
                })
                    .then(function (response) {
                        console.log(response.data);
                        self.gridData2 = response.data;

                        //将付款码发送给机器
                        var qttstr = {}; //定义消息（可以为字符串，对象等）
                        qttstr.paymentcode = self.paymentcode;

                        mqttclient.publish('super/machine/paymentcode',JSON.stringify(qttstr),{ qos: 2});

                        self.gridData2['money'] = self.goodsnum * self.gridData['money'];
                        self.paymentdialogTableVisible=true;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            goodshandleChange(value) {
                //console.log(this.gridData.curamount);
                if(value > this.gridData.curamount) {
                    this.$message({
                        message: '已经超过当前货品数量！',
                        type: 'warning'
                    });
                    return;
                }
            },
            goodscontent(goodsid) {
                var self = this;
                var isGetGoods = false;

                for(var i=0;i<this.goods.length;i++) {
                  if(this.goods[i].id == goodsid) {
                      this.gridData = this.goods[i];
                      this.gridData['goodsid'] = this.goods[i].goodsid;
                      console.log(this.goods[i].goodsid)
                      isGetGoods = true;
                      this.loading=true;
                      break;
                  }
                }

                if(isGetGoods) {
                    self.loading=false;
                    self.goodsnum=1;
                    self.dialogTableVisible=true;
                }
            },
            handleSelect(key, keyPath) {
                var self = this;

                this.loading=true;

                axios.get("{:url('api/mobile/getAllGoodsByCategory')}", {
                    params: {
                        categoryid : key,
                        userid : self.playerid,
                        machineid : self.machine_id,
                    }
                })
                    .then(function (response) {
                        //console.log(response.data);
                        self.goods = response.data;
                        self.loading=false;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            Initswiperslide : function() {
                if(swiperslide != null) return;

                swiperslide = new Swiper('.swiper-container', {
                    slidesPerView: 3,
                    slidesPerColumn: 2,
                    slidesPerGroup : 6,
                    spaceBetween: 30,
                    //slidesPerColumnFill : 'row',
                    observer:true,//修改swiper自己或子元素时，自动初始化swiper
                    observeParents:true,//修改swiper的父元素时，自动初始化swiper
                    navigation: {
                        nextEl: '.swiper-button-next',
                        prevEl: '.swiper-button-prev',
                    },
                });
            },
            InitVideoPlayer : function () {
                if(myplayer != null) return;

                myplayer = videojs('my-player', {
                    "width":"100%",
                    "height":"100",
                    "aspectRatio":"16:9",
                    "poster": "//vjs.zencdn.net/v/oceans.png",
                    "controls": false,
                    "autoplay" :true,
                    "techOrder" : [ "html5" ],
                    "loop":true,
                    "muted":false,
                    "preload": 'auto',
                    "isFullscreen":true
                });
            },
            InitOther : function () {
                var self = this;

                //获取所有的商品类别
                //var location = 'http://cms.o4.com/api/mobile/getAllGoodsCategory';

                axios.get("{:url('api/mobile/getAllGoodsCategory')}", {
                    params: {

                    }
                })
                    .then(function (response) {
                        //console.log(response.data);
                        self.goodscategorys = response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            InitMqtt: function () {
                var self = this;

                this.loading=true;

                var options = {
                    //mqtt客户端的id，这里面应该还可以加上其他参数，具体看官方文档
                    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
                    //username:'admin',
                    //password:'112233'
                }

                mqttclient = mqtt.connect("ws://127.0.0.1:19011/mqtt",options) // you add a ws:// url here

                //建立连接
                mqttclient.on('connect', function () {
                    console.log("机器服务器连接成功!")
                    //订阅主题 presence
                    var subscribes = ['super/machine/advertfullscreen',
                        'super/machine/refreshscreen',
                        'super/machine/releaseadvert',
                        'super/machine/getmachineinfo/return'];

                    mqttclient.subscribe(subscribes, function (err) {
                        if (!err) {
                            console.log("消息订阅成功.")

                            //获取当前使用机器的信息
                            mqttclient.publish('super/machine/getmachineinfo','');
                        }else{
                            //打印错误
                            console.log(err)
                        }
                    })
                })

                //如果连接错误，打印错误
                mqttclient.on('error', function (err) {
                    console.log(err)
                    mqttclient.end()
                })

                //如果client订阅主题成功，那么这里就是当接收到自己订阅主题的处理逻辑
                mqttclient.on('message', function (topic, message) {
                    // message is Buffer,此处就是打印消息的具体内容
                    var msg = message.toString();
                    var topicstr = topic.toString();

                    console.log(topic.toString() + '-> ' + message.toString())

                    try{
                        var params = JSON.parse( msg );

                        if(topicstr == 'super/machine/advertfullscreen') {
                            myplayer.requestFullscreen();
                        }
                        else if(topicstr == 'super/machine/refreshscreen') {
                            window.location.reload();
                        }
                        else if(topicstr == 'super/machine/getmachineinfo/return') {
                            self.machine_id = params.machine_id;
                            self.playerid = params.playerid;

                            console.log("当前机器：" + self.machine_id + " 当前用户:" + self.playerid);

                            axios.get("{:url('api/mobile/getAllGoodsByCategory')}", {
                                params: {
                                    categoryid : -1,
                                    userid : self.playerid,
                                    machineid : self.machine_id,
                                }
                            })
                                .then(function (response) {
                                    //console.log(response.data);
                                    self.goods = response.data;
                                    self.loading=false;
                                })
                                .catch(function (error) {
                                    console.log(error);
                                });
                        }
                        else if(topicstr == 'super/machine/releaseadvert') {
                            if(params.videotype == '' || params.advertsrc == '') {
                                self.videoisplay=false;
                            }
                            else {
                                myplayer.src({ type: params.videotype, src: params.advertsrc });
                                myplayer.load(params.advertsrc);
                                myplayer.play();
                                self.videoisplay=true;
                            }
                        }
                    }catch(exception){
                        console.info(exception.message);
                    }
                })
            }
        }
    });
</script>

</body>
</html>

